package com.guiwu.controller;

import com.guiwu.config.DatabaseConnectionChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 提供应用和数据库健康状态检查
 */
@RestController
@RequestMapping("/health")
public class HealthController {

    @Autowired
    private DatabaseConnectionChecker databaseConnectionChecker;

    /**
     * 应用健康检查
     * @return 健康状态信息
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> health = new HashMap<>();
        
        // 应用基本信息
        health.put("status", "UP");
        health.put("timestamp", LocalDateTime.now());
        health.put("application", "物品归纳系统");
        health.put("version", "1.0.0");
        
        // 数据库健康检查
        boolean dbHealthy = databaseConnectionChecker.checkDatabaseConnection();
        Map<String, Object> database = new HashMap<>();
        database.put("status", dbHealthy ? "UP" : "DOWN");
        database.put("info", databaseConnectionChecker.getDatabaseInfo());
        health.put("database", database);
        
        // 根据数据库状态决定整体状态
        if (!dbHealthy) {
            health.put("status", "DOWN");
            return ResponseEntity.status(503).body(health);
        }
        
        return ResponseEntity.ok(health);
    }

    /**
     * 数据库连接检查
     * @return 数据库连接状态
     */
    @GetMapping("/db")
    public ResponseEntity<Map<String, Object>> databaseHealth() {
        Map<String, Object> response = new HashMap<>();
        
        boolean isHealthy = databaseConnectionChecker.checkDatabaseConnection();
        String info = databaseConnectionChecker.getDatabaseInfo();
        
        response.put("status", isHealthy ? "UP" : "DOWN");
        response.put("timestamp", LocalDateTime.now());
        response.put("info", info);
        
        if (isHealthy) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(503).body(response);
        }
    }

    /**
     * 简单的ping检查
     * @return pong响应
     */
    @GetMapping("/ping")
    public ResponseEntity<Map<String, Object>> ping() {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "pong");
        response.put("timestamp", LocalDateTime.now());
        response.put("status", "UP");
        return ResponseEntity.ok(response);
    }
}
